package cn.tonyandmoney.warescanapp.ui

import android.Manifest
import android.os.Bundle
import com.zlzsy.app.base.ui.PermissionRequestActivity
import cn.tonyandmoney.warescanapp.MainActivity
import cn.tonyandmoney.warescanapp.R
import cn.tonyandmoney.warescanapp.rfid.BT_ADDRESS
import cn.tonyandmoney.warescanapp.rfid.RFIdUtils
import cn.tonyandmoney.warescanapp.rfid.event.ConnectEvent
import com.dhh.rxlifecycle2.RxLifecycle
import org.jetbrains.anko.*

/**
 * Created by niantuo on 2018/4/1.
 * 首先第一步，应该是连接蓝牙，
 */
class BluetoothListActivity : AnkoLogger, PermissionRequestActivity(),PermissionRequestActivity.PermissionEvent {
    private val mUtils = RFIdUtils.utils

    private val REQ_PERMISSION = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE)

    override fun initView() {
        verticalLayout {
            textView {
                padding = dip(15)
                text = "开始连接蓝牙"
                setOnClickListener { connect() }
                backgroundResource = R.color.colorAccent
            }.lparams(wrapContent, wrapContent) {
                margin = dip(10)
            }
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        mUtils.register<ConnectEvent>()
                .compose(RxLifecycle.with(this).bindOnDestroy())
                .subscribe { onConnectState(it) }

        requirePermissions(11,REQ_PERMISSION,this)
    }

    override fun permissionDenied(permissions: Array<String>) {

    }

    override fun permissionGranted() {

    }

    private fun connect() {
        showLoadingDialog(R.string.is_connecting_to_rfid)
        mUtils.commandLib.connectBTDeviceByAddress(BT_ADDRESS)
    }

    private fun onConnectState(event: ConnectEvent) {
        when (event.code) {
            ConnectEvent.CODE_SUCCESS -> {
                startActivity<MainActivity>()
                finish()
            }
            ConnectEvent.CODE_FAILED -> {
                hideLoadingDialog()
                longToast("设备连接失败，请确认设备已打开。")
            }
        }
    }

    override fun onDestroy() {
        hideLoadingDialog()
        super.onDestroy()
    }

}